/*
 
 * To change this template, choose Tools | Templates
 
 * and open the template in the editor.
 
 */

package gui;

import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.DefaultListModel;

import controlador.ControladorCurso;

import java.awt.Color;
import java.util.List;

import bean.Curso;

/**
 * 
 * 
 * 
 * @author STI
 */

public class PainelCurso extends javax.swing.JPanel {

	/**
	 * 
	 * Creates new form PainelCurso
	 */

	DefaultTableModel tabelaCurso = new DefaultTableModel(new String[] {
			"Código", "Nome", "Carga Horária" }, 0);

	public PainelCurso() {

		initComponents();
		listagem();

	}

	/**
	 * * This method is called from within the constructor to initialize the
	 * form.
	 * 
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * 
	 * regenerated by the Form Editor.
	 */

	@SuppressWarnings("unchecked")
	// <editor-fold defaultstate="collapsed"
	// desc="Generated Code">//GEN-BEGIN:initComponents
	private void initComponents() {

		cursoCodigo = new javax.swing.JTextField();

		jLabel1 = new javax.swing.JLabel();

		jLabel2 = new javax.swing.JLabel();

		cursoNome = new javax.swing.JTextField();

		jLabel3 = new javax.swing.JLabel();

		cursoCarga = new javax.swing.JTextField();

		jPanelBotoes = new javax.swing.JPanel();

		jButtonSalvar = new javax.swing.JButton();

		jButtonExcluir = new javax.swing.JButton();

		jButtonBuscar = new javax.swing.JButton();

		jButtonCancelar = new javax.swing.JButton();

		jButtonListar = new javax.swing.JButton();

		//jButtonEditar = new javax.swing.JButton();

		jButtonAtualizar = new javax.swing.JButton();

		jLabel4 = new javax.swing.JLabel();

		jScrollPane1 = new javax.swing.JScrollPane();

		jTableCurso = new javax.swing.JTable();

		setMaximumSize(new java.awt.Dimension(830, 512));

		setMinimumSize(new java.awt.Dimension(830, 512));

		setPreferredSize(new java.awt.Dimension(830, 512));

		cursoCodigo.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
		cursoCodigo.setEnabled(false);
		cursoCodigo.setBackground(Color.black);
		cursoCodigo.setForeground(new java.awt.Color(255, 255, 255));

		jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

		jLabel1.setText("Cod. Curso: ");

		jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

		jLabel2.setText("Nome: ");

		cursoNome.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

		jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

		jLabel3.setText("Carga Horária:");

		cursoCarga.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

		jPanelBotoes.setLayout(new java.awt.GridBagLayout());

		jButtonSalvar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

		jButtonSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource(
				"/Imagens/Add.png"))); // NOI18N

		jButtonSalvar.setText("Salvar");

		jButtonSalvar.addActionListener(new java.awt.event.ActionListener() {

			public void actionPerformed(java.awt.event.ActionEvent evt) {

				jButtonSalvarActionPerformed(evt);

			}

		});

		jPanelBotoes.add(jButtonSalvar, new java.awt.GridBagConstraints());

		jButtonExcluir.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

		jButtonExcluir.setIcon(new javax.swing.ImageIcon(getClass()
				.getResource("/Imagens/Delete.png"))); // NOI18N

		jButtonExcluir.setText("Excluir");

		jButtonExcluir.addActionListener(new java.awt.event.ActionListener() {

			public void actionPerformed(java.awt.event.ActionEvent evt) {

				jButtonExcluirActionPerformed(evt);

			}

		});

		jPanelBotoes.add(jButtonExcluir, new java.awt.GridBagConstraints());

		
		jButtonBuscar.addActionListener(new java.awt.event.ActionListener() {

			public void actionPerformed(java.awt.event.ActionEvent evt) {

				jButtonBuscarActionPerformed(evt);

			}

		});
		
		jButtonBuscar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

		jButtonBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource(
				"/Imagens/Find.png"))); // NOI18N

		jButtonBuscar.setText("Buscar");

		
		jPanelBotoes.add(jButtonBuscar, new java.awt.GridBagConstraints());

		jButtonCancelar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

		jButtonCancelar.setIcon(new javax.swing.ImageIcon(getClass()
				.getResource("/Imagens/Abort.png"))); // NOI18N

		jButtonCancelar.setText("Cancelar");

		jButtonCancelar.addActionListener(new java.awt.event.ActionListener() {

			public void actionPerformed(java.awt.event.ActionEvent evt) {

				jButtonCancelarActionPerformed(evt);

			}

		});

		jPanelBotoes.add(jButtonCancelar, new java.awt.GridBagConstraints());

		jButtonListar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

		jButtonListar.setIcon(new javax.swing.ImageIcon(getClass().getResource(
				"/Imagens/List.png"))); // NOI18N

		jButtonListar.setText("Listar");

		jButtonListar.addActionListener(new java.awt.event.ActionListener() {

			public void actionPerformed(java.awt.event.ActionEvent evt) {

				jButtonListarActionPerformed(evt);

			}

		});

		jPanelBotoes.add(jButtonListar, new java.awt.GridBagConstraints());

		//jButtonEditar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

		//jButtonEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource(
		//		"/Imagens/Application.png"))); // NOI18N

		//jButtonEditar.setText("Editar");
		
		//jPanelBotoes.add(jButtonEditar, new java.awt.GridBagConstraints());

		jButtonAtualizar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

		jButtonAtualizar.setIcon(new javax.swing.ImageIcon(getClass()
				.getResource("/Imagens/Load.png"))); // NOI18N

		jButtonAtualizar.setText("Atualizar");
		
		jButtonAtualizar.addActionListener(new java.awt.event.ActionListener() {

			public void actionPerformed(java.awt.event.ActionEvent evt) {

				jButtonAtualizarActionPerformed(evt);

			}

		});

		jPanelBotoes.add(jButtonAtualizar, new java.awt.GridBagConstraints());

		jLabel4.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N

		jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

		jLabel4.setText("Curso");

		jTableCurso.setModel(tabelaCurso);

		jTableCurso.getTableHeader().setReorderingAllowed(false);
		//jTableCurso.setColumnSelectionAllowed(true);
		jScrollPane1.setViewportView(jTableCurso);
		//jTableCurso.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);

		this.setLayout(layout);

		layout.setHorizontalGroup(

		layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

				.addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE,
						javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)

				.addGroup(
						layout.createSequentialGroup()

								.addContainerGap()

								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.LEADING)

												.addComponent(jScrollPane1)

												.addGroup(
														layout.createSequentialGroup()

																.addGroup(
																		layout.createParallelGroup(
																				javax.swing.GroupLayout.Alignment.LEADING)

																				.addComponent(
																						jLabel1)

																				.addComponent(
																						jLabel3)

																				.addComponent(
																						jLabel2))

																.addGap(18, 18,
																		18)

																.addGroup(
																		layout.createParallelGroup(
																				javax.swing.GroupLayout.Alignment.LEADING)

																				.addComponent(
																						cursoCodigo,
																						javax.swing.GroupLayout.PREFERRED_SIZE,
																						266,
																						javax.swing.GroupLayout.PREFERRED_SIZE)

																				.addComponent(
																						cursoCarga,
																						javax.swing.GroupLayout.PREFERRED_SIZE,
																						266,
																						javax.swing.GroupLayout.PREFERRED_SIZE)

																				.addComponent(
																						cursoNome,
																						javax.swing.GroupLayout.PREFERRED_SIZE,
																						266,
																						javax.swing.GroupLayout.PREFERRED_SIZE))

																.addGap(0,
																		0,
																		Short.MAX_VALUE)))

								.addContainerGap())

				.addComponent(jPanelBotoes,
						javax.swing.GroupLayout.Alignment.TRAILING,
						javax.swing.GroupLayout.DEFAULT_SIZE, 830,
						Short.MAX_VALUE)

		);

		layout.setVerticalGroup(

		layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

				.addGroup(
						layout.createSequentialGroup()

								.addComponent(jLabel4,
										javax.swing.GroupLayout.PREFERRED_SIZE,
										50,
										javax.swing.GroupLayout.PREFERRED_SIZE)

								.addGap(18, 18, 18)

								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.BASELINE)

												.addComponent(jLabel1)

												.addComponent(
														cursoCodigo,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														javax.swing.GroupLayout.PREFERRED_SIZE))
													

								.addGap(18, 18, 18)

								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.BASELINE)

												.addComponent(jLabel2)

												.addComponent(
														cursoNome,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														javax.swing.GroupLayout.PREFERRED_SIZE))

								.addGap(18, 18, 18)

								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.BASELINE)

												.addComponent(jLabel3)

												.addComponent(
														cursoCarga,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														javax.swing.GroupLayout.PREFERRED_SIZE))

								.addGap(18, 18, 18)

								.addComponent(jScrollPane1,
										javax.swing.GroupLayout.DEFAULT_SIZE,
										263, Short.MAX_VALUE)

								.addPreferredGap(
										javax.swing.LayoutStyle.ComponentPlacement.RELATED)

								.addComponent(jPanelBotoes,
										javax.swing.GroupLayout.PREFERRED_SIZE,
										52,
										javax.swing.GroupLayout.PREFERRED_SIZE))

		);

	}// </editor-fold>//GEN-END:initComponents

	// vincular ao butão cadastrar

	private void jButtonSalvarActionPerformed(java.awt.event.ActionEvent evt) {

		if (cursoCarga.getText().equals("") || cursoNome.getText().equals("")) {

			JOptionPane.showMessageDialog(null,
					"O preenchimento de todos os campos é obrigatório!");

		} else {
			Curso curso = null;

			try {
			    int idCurso = 1 ; 
				ControladorCurso cc = new ControladorCurso();
				Curso c;
				 System.out.println("Ta preso no while");
				while (true) {
					c = cc.consultarCurso(idCurso);
					if (c!=null) {
						idCurso++;
						 System.out.println("Ta preso no while");
					} else {
		                  c = new Curso();
		                  c.setCodCurso(idCurso);
		                  c.setCarga_horaria(Integer.parseInt(cursoCarga.getText()));
		                  c.setNome(cursoNome.getText());
			              cc.salva(c);
		                  break;
		                 
					}
		          }

			} catch (Exception er) {
				JOptionPane
						.showMessageDialog(
								null,
								"Erro ao cadastrar, verifique se todos os campos estão devidamente preenchidos!");
				limparCampos();

				listagem();
			}

			limparCampos();

			listagem();

		}

	}

	private void jButtonExcluirActionPerformed(java.awt.event.ActionEvent evt) {
		int delete;
		if (jTableCurso.getSelectedRowCount()==0)  {
			JOptionPane.showMessageDialog(null,
					"Clique na linha onde encontra-se o curso que deseja excluir!");
		} else {
			int linha = jTableCurso.getSelectedRow();
			ControladorCurso cc = new ControladorCurso();
			 cursoCodigo.setText(jTableCurso.getValueAt(linha, 0) + "");
	            cursoNome.setText(jTableCurso.getValueAt(linha, 1) + "");
	            cursoCarga.setText(jTableCurso.getValueAt(linha, 2)+ "");
	            delete = (int) jTableCurso.getValueAt(linha, 0);
			int opcao = JOptionPane.showConfirmDialog(null,
					"Tem certeza que deseja excluir?", "Excluir!",
					JOptionPane.YES_NO_OPTION);

			if (opcao == JOptionPane.YES_OPTION) {
				try {				
					cc.exluir(delete);
					limparCampos();
					listagem();
				} catch (Exception e) {
					JOptionPane.showMessageDialog(null,
							"Está disciplina está vinculada a algum curso, desvincule-a para realizar a exclusão!");
					limparCampos();
					listagem();
				} 
			} else {
				JOptionPane.showMessageDialog(null, "Exclusão cancelada!");
				limparCampos();	
			}
		}
	}

	private void jButtonCancelarActionPerformed(java.awt.event.ActionEvent evt) {
		limparCampos();
	}

	private void jButtonListarActionPerformed(java.awt.event.ActionEvent evt) {
		listagem();
	}

	private void jButtonBuscarActionPerformed(java.awt.event.ActionEvent evt) {
		int delete;
		if (jTableCurso.getSelectedRowCount()==0)  {
			JOptionPane.showMessageDialog(null,
					"Clique na linha onde encontra-se o curso que deseja alterar!");
			jButtonAtualizar.setEnabled(false);
		} else {
			int linha = jTableCurso.getSelectedRow();
				ControladorCurso cc = new ControladorCurso();
				cursoCodigo.setText(jTableCurso.getValueAt(linha, 0) + "");
	            cursoNome.setText(jTableCurso.getValueAt(linha, 1) + "");
	            cursoCarga.setText(jTableCurso.getValueAt(linha, 2)+ "");
	            jButtonAtualizar.setEnabled(true);
	            delete = (int) jTableCurso.getValueAt(linha, 0);	
		}

	}

	private void jButtonAtualizarActionPerformed(java.awt.event.ActionEvent evt) {
		Curso c = null;
		int num;
		if (cursoCodigo.getText().equals(""))  {
			JOptionPane.showMessageDialog(null,
					"Clique e/ou Pesquise pelo curso que deseja atualizar!");
		} else {
			c = new Curso();
			ControladorCurso cc = new ControladorCurso();
			    c.setCodCurso(Integer.parseInt(cursoCodigo.getText()));
	            c.setNome(cursoNome.getText());
	            c.setCarga_horaria(Integer.parseInt(cursoCarga.getText()));

			int opcao = JOptionPane.showConfirmDialog(null,
					"Tem certeza que deseja alterar?", "Alterar!",
					JOptionPane.YES_NO_OPTION);

			if (opcao == JOptionPane.YES_OPTION) {
				try {				
					cc.salva(c);
					limparCampos();
					listagem();
				} catch (Exception e) {
					JOptionPane.showMessageDialog(null,
							"Não existe curso com esse código!");
					limparCampos();
					listagem();
				} 
			} else {
				JOptionPane.showMessageDialog(null, "Exclusão cancelada!");
				limparCampos();	
			}
		}

	}

	// Variables declaration - do not modify//GEN-BEGIN:variables

	private javax.swing.JTextField cursoCarga;
	private javax.swing.JTextField cursoCodigo;
	private javax.swing.JTextField cursoNome;
	private javax.swing.JButton jButtonAtualizar;
	private javax.swing.JButton jButtonBuscar;
	private javax.swing.JButton jButtonCancelar;
	private javax.swing.JButton jButtonEditar;
	private javax.swing.JButton jButtonExcluir;
	private javax.swing.JButton jButtonListar;
	private javax.swing.JButton jButtonSalvar;
	private javax.swing.JLabel jLabel1;
	private javax.swing.JLabel jLabel2;
	private javax.swing.JLabel jLabel3;
	private javax.swing.JLabel jLabel4;
	private javax.swing.JPanel jPanelBotoes;
	private javax.swing.JScrollPane jScrollPane1;
	private javax.swing.JTable jTableCurso;

	// End of variables declaration//GEN-END:variables

	private void limparCampos() {
		cursoCarga.setText("");
		cursoCodigo.setText("");
		cursoNome.setText("");
		jButtonAtualizar.setEnabled(false);
	}

	private void listagem() {
		tabelaCurso.setNumRows(0);
		ControladorCurso cc = new ControladorCurso();
		if (cc.lista() == null) {
			JOptionPane.showMessageDialog(null,
					"Não há cursos no banco de dados!");
		} else {
			List<Curso> lista = cc.lista();
			int t = lista.size();
			for (int i = 0; i < t; i++) {
				Curso curso = lista.get(i);
				tabelaCurso.addRow(new Object[] { curso.getCodCurso(),
						curso.getNome(), curso.getCarga_horaria() });

			}
		}
		jButtonAtualizar.setEnabled(false);
	}	
}
